package org.yijiaganxi.common.exception;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yijiaganxi.common.GlobalConstants;
import org.yijiaganxi.common.res.R;


import lombok.extern.slf4j.Slf4j;


@Slf4j
@Component
@RestControllerAdvice
public class ExceptionsHandler {

	static {
		System.err.println(".......................  异常处理器初始化 ");
	}
	
	@ExceptionHandler(IllegalStateException.class)
	@ResponseBody
	public Object illegalStateHandler(IllegalStateException e) {
		e.printStackTrace();
		log.error(GlobalConstants.SERVER_EXCEPTION_MESSAGE, e.getMessage());
		return R.error(e.getMessage());
	}

	@ExceptionHandler(RuntimeException.class)
	@ResponseBody
	public Object runtimeHandler(RuntimeException e) {
		e.printStackTrace();
		log.error(GlobalConstants.SERVER_EXCEPTION_MESSAGE, e.getMessage());
		return R.error(e.getMessage());
	}

	@ExceptionHandler(IndexOutOfBoundsException.class)
	@ResponseBody   
	public Object runtimeHandler(IndexOutOfBoundsException e) {
		e.printStackTrace();
		return R.error(e.getMessage());
	}

	@org.springframework.web.bind.annotation.ExceptionHandler(BindException.class)
	public String handleBindException(HttpServletRequest request, BindException exception) {
		List<FieldError> allErrors = exception.getFieldErrors();
		StringBuilder sb = new StringBuilder();
		for (FieldError errorMessage : allErrors) {
			sb.append(errorMessage.getField()).append(": ").append(errorMessage.getDefaultMessage()).append(", ");
		}
		System.out.println(sb.toString());
		return sb.toString();
	}

	@org.springframework.web.bind.annotation.ExceptionHandler(ConstraintViolationException.class)
	public String handleBindException2(HttpServletRequest request, ConstraintViolationException exception) {
		String message = exception.getMessage();
		if (message.contains(".")) {
			String[] split = message.split("\\.");
			message = split[1];
		}
		return message;
	}

}
